<?php

namespace app\store\controller\campus;

use app\store\controller\Controller;
use app\store\model\campus\Campus as CampusModel;
use app\store\model\campus\Teacher as TeacherModel;

/**
 * 校区教师控制器
 * Class Teacher
 * @package app\store\controller\campus
 */
class Teacher extends Controller
{
    /**
     * 教师列表
     * @param int $campus_id
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($campus_id = 0, $search = '')
    {
        // 教师列表
        $model = new TeacherModel;
        $list = $model->getList(-1, $campus_id, $search);

        // 校区列表
        $campusList = CampusModel::getAllList();

        return $this->fetch('index', compact('list', 'campusList'));
    }

    /**
     * 添加教师
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function add()
    {
        $model = new TeacherModel;
        if (!$this->request->isAjax()) {
            // 校区列表
            $campusList = CampusModel::getAllList();
            return $this->fetch('add', compact('campusList'));
        }
        // 新增记录
        if ($model->add($this->postData('teacher'))) {
            return $this->renderSuccess('添加成功', url('campus.teacher/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑教师
     * @param $teacher_id
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function edit($teacher_id)
    {
        // 教师详情
        $model = TeacherModel::detail($teacher_id);
        if (!$this->request->isAjax()) {
            // 校区列表
            $campusList = CampusModel::getAllList();
            return $this->fetch('edit', compact('model', 'campusList'));
        }
        // 新增记录
        if ($model->edit($this->postData('teacher'))) {
            return $this->renderSuccess('更新成功', url('campus.teacher/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除教师
     * @param $teacher_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($teacher_id)
    {
        // 教师详情
        $model = TeacherModel::detail($teacher_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}